export default class CA {

  constructor() {
    this.SM2_OID = '1.2.156.112562.2.1.1.1'
    this.RSA_OID = '2.16.840.1.113732.2'

    this.userUid = ''
    this.userCertId = window.localStorage.getItem('CA_USER_CERT_ID') || ''
    this.userCertBase64 = ''
    this.userCertList = []
    
    //设置更新证书列表
    this._updateUserCertList()

    //当前用户证书id存在时，更新用户证书base64
    if(this.userCertId){
      this.updateUserCertBase64()
    }
  }

  /**
  * 改变证书
  */
  async chooseCert(userCertId) {
    try {
      this.userCertId = userCertId
      await this.updateUserCertBase64()
    } catch (error) {
      console.log(error)
    }
  }

  /**
   * 校验证书口令
   * @param {string} password
   */
  login(password) {
    return new Promise((resolve, reject) => {
      xtxasyn.SOF_Login(this.userCertId, password, (res) => {
        if(res.retVal){
          resolve(res)
        }else{
          new Error('SOF_Login:校验证书口令失败=>' + JSON.stringify(res))
          reject({message: 'CA登录失败', code: 0})
        }
      }, {userCertId: this.userCertId})
    })
  }

  /**
   * 获取证书扩展信息
   * 获取“证书用户唯一标识”
   */
  getUserCertInfo() {
    return new Promise((resolve, reject) => {
      xtxasyn.SOF_GetCertInfoByOid(this.userCertBase64, this.SM2_OID, (res) => {
        if(res.retVal){
          this.userUid = res.retVal
          resolve(res)
        }else{
          new Error('SOF_GetCertInfoByOid:获取“用户证书唯一标识”失败=>' + JSON.stringify(res))
          reject({message: '获取用户证书唯一标识失败', code: 0})
        }
      })
    })
  }

  /**
   * 更新获取证书base64
   */
  updateUserCertBase64() {
    return new Promise((resolve, reject) => {
      xtxasyn.SOF_ExportUserCert(this.userCertId, (res) => {
        if (res.retVal) {
          this.userCertBase64 = res.retVal
          resolve(res.retVal)
        } else {
          reject(new Error('SOF_ExportUserCert:获取证书base64失败=>' + JSON.stringify(res)))
        }
      })
    })
  }

  /**
   * 验证服务端随机数签名
   * @param {*} serverCert  服务端证书
   * @param {*} random      服务端随机数
   * @param {*} randomSign  服务端随机数签名
   */
  verifyRemoteSigned(serverCert, random, randomSign) {
    return new Promise((resolve, reject) => {
      xtxasyn.SOF_VerifySignedData(serverCert, random, randomSign, (res) => {
        if (res.retVal === true) {
          resolve(res)
        } else {
          reject({message: '验证服务端随机数签名失败', code: 0})
        }
      })
    })
  }

  /**
   * 数据签名
   * @param {*} data 
   * @returns 
   */
  signData(data){
    return new Promise((resolve, reject) => {
      xtxasyn.SOF_SignData(this.userCertId, data, (res)=>{
        if(res.retVal){
          resolve(res)
        }else{
          reject(new Error('SOF_SignData:数据签名失败=>' + JSON.stringify(res)))
        }
      })
   })
  }

  /**
   * 获取证书列表
   * @returns 
   */
  _updateUserCertList() {
    xtxasyn.SOF_GetUserList((res) => {
      let retVal = res.retVal

      let arr = retVal.split('&&&')
      for (let i = 0; i < arr.length; i++) {
        if (arr[i]) {
          let valArr = arr[i].split('||')
          this.userCertList.push({
            name: valArr[0],
            value: valArr[1]
          })
        }
      }
    });
  }

  getUserCertList() {

    return new Promise((resolve, reject) => {
      xtxasyn.SOF_GetUserList((res) => {
        let retVal = res.retVal

        this.userCertList = []

        let arr = retVal.split('&&&')
        for (let i = 0; i < arr.length; i++) {
          if (arr[i]) {
            let valArr = arr[i].split('||')
            this.userCertList.push({
              name: valArr[0],
              value: valArr[1]
            })
          }
        }

        resolve(this.userCertList)
      })
    })
  
  }

  /**
   * 获取签章图片base64
   * @returns 
   */
  getPicture() {
    return new Promise((resolve, reject) => {
      if(this.userCertId){
        let bstrConName = this.userCertId.split('/')[0]
        xtxasyn.GetPicture(bstrConName, (res)=>{
          if(res.retVal){
            resolve(res)
          }else{
            reject({message: '获取签章图片失败', code: 0})
          }
        })
      }
    })
  }

  /**
   * 方法验证是否参数完整
   * @returns {boolean} true:参数完整，false：参数不完整
   */
  _checkValidation() {
    if (this.userCertId) {
      return true
    } else {
      new Error('请选择证书')
      return false
    }
  }

}